<!--
  * 工单生产计划
  *
  * @Author:    lmabbe
  * @Date:      2025-06-26 19:38:05
  * @Copyright  lmabbe
-->
<template>
  <a-modal :destroyOnClose="true" :maskClosable="false" :open="visibleFlag" :title="form.planId ? '编辑' : '添加'" :width="850" @cancel="onClose">
    <a-form ref="formRef" :label-col="{ style: 'width: 100px; display: inline-block; vertical-align: inherit;' }" :model="form" :rules="rules">
      <a-row>
        <a-input v-model:value="form.planId" hidden placeholder="生产计划ID" style="width: 100%" />
        <a-col :span="12">
          <a-form-item label="工单编号" name="workOrderCode">
            <TableSelect
              v-model:modelValue="form.workOrderCode"
              :columns="[
                { title: '工单编号', dataIndex: 'workOrderCode', key: 'workOrderCode' },
                { title: '成品/机型编号', dataIndex: 'materialCode', key: 'materialCode' },
                { title: '成品/机型名称', dataIndex: 'materialName', key: 'materialName' },
                { title: '成品/机型规格', dataIndex: 'materialSpec', key: 'materialSpec' },
                { title: '归属客户', dataIndex: 'belongCustomerAbbreviation', key: 'belongCustomerAbbreviation' },
              ]"
              :options="workOrderData"
              :placeholder="'输入成品/机型编号/名称/规格'"
              @search="handleWorkOrderSearch"
              @select="handleWorkOrderSelect"
            />
          </a-form-item>
        </a-col>
        <!--        <a-col :span="12">
                  <a-form-item label="制程类别" name="processCategory">
                    <DictSelect v-model:value="form.processCategory" dict-code="PROCESS_CATEGORY" placeholder="制程类型" width="100%" />
                  </a-form-item>
                </a-col>-->
        <a-col :span="12">
          <a-form-item label="生成产线" name="lineId">
            <a-select
              v-model:value="form.lineId"
              :allowClear="true"
              :style="`width: 100%`"
              placeholder="请选择归属线别"
              @change="
                (value) => {
                  form.lineName = productLineData.find((item) => item.lineId === value).lineName;
                  form.processCategory = productLineData.find((item) => item.lineId === value).processCategory;
                }
              "
            >
              <a-select-option v-for="item in productLineData" :key="item.lineId" :value="item.lineId">
                {{ item.lineName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="站位表版本" name="positionVer">
            <a-input v-model:value="form.positionVer" placeholder="站位表版本" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="计划生产数量" name="planProductionQty">
            <a-input-number v-model:value="form.planProductionQty" :max="maxCount" :min="1" placeholder="计划生产数量" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="计划生产版面" name="planProductionLayout">
            <DictSelect v-model:value="form.planProductionLayout" dict-code="PRODUCT_BRAND" placeholder="制程类型" width="100%" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="计划开始时间" name="planStartTime">
            <a-date-picker
              v-model:value="form.planStartTime"
              placeholder="计划开始时间"
              show-time
              style="width: 100%"
              valueFormat="YYYY-MM-DD HH:mm:ss"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="计划结束时间" name="planEndTime">
            <a-date-picker
              v-model:value="form.planEndTime"
              placeholder="计划结束时间"
              show-time
              style="width: 100%"
              valueFormat="YYYY-MM-DD HH:mm:ss"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="标准产能" name="standardCapacity">
            <a-input-number v-model:value="form.standardCapacity" placeholder="标准产能 数量/h" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="form.remark" placeholder="备注" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';

  import { productionPlanApi } from '/@/api/business/product/order/production-plan-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableSelect from '/@/components/TableSelect/index.vue';
  import { workOrderInfoApi } from '/@/api/business/product/order/work-order-info-api.js';
  import DictSelect from '/@/components/support/dict-select/index.vue';
  import { productLineInfoApi } from '/@/api/business/product/line/product-line-info-api.js'; // ------------------------ 事件 ------------------------

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    loadProductLine();
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
    planId: undefined, //生产计划ID
    workOrderId: undefined, //工单ID
    workOrderCode: undefined, //工单编号
    processCategory: undefined, //制程类别
    lineId: undefined, //产线ID
    lineName: undefined, //产线名称
    positionVer: undefined, //站位表版本
    planProductionQty: undefined, //计划生产数量
    planProductionLayout: undefined, //计划生产版面
    standardCapacity: undefined, //标准产能 数量/h
    planStartTime: undefined, //计划开始时间
    planEndTime: undefined, //计划结束时间
    remark: undefined, //备注
  };

  let form = reactive({ ...formDefault });

  const rules = {
    planId: [{ required: true, message: '生产计划ID 必填' }],
    workOrderId: [{ required: true, message: '工单ID 必填' }],
    workOrderCode: [{ required: true, message: '工单编号 必填' }],
    processCategory: [{ required: true, message: '制程类别 必填' }],
    lineId: [{ required: true, message: '产线ID 必填' }],
    positionVer: [{ required: true, message: '站位表版本 必填' }],
    planProductionQty: [{ required: true, message: '计划生产数量 必填' }],
    planProductionLayout: [{ required: true, message: '计划生产版面 必填' }],
    planStartTime: [{ required: true, message: '计划开始时间 必填' }],
    planEndTime: [{ required: true, message: '计划结束时间 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      if (form.planId) {
        await productionPlanApi.update(form);
      } else {
        await productionPlanApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  const workOrderData = ref();
  const handleWorkOrderSearch = (searchValue) => {
    let param = {
      workOrderCode: searchValue,
      customerCode: form.customerCode,
    };
    workOrderInfoApi.getAvailableOrder(param).then((res) => {
      workOrderData.value = res.data;
    });
  };

  const maxCount = ref();
  const handleWorkOrderSelect = (value) => {
    form.workOrderId = value.record.workOrderId;
    form.workOrderCode = value.record.workOrderCode;
    maxCount.value = value.record.productionQty;
  };

  const productLineData = ref();

  function loadProductLine() {
    productLineInfoApi.all().then((res) => {
      productLineData.value = res.data;
    });
  }

  defineExpose({
    show,
  });
</script>
